#include "../StdAfx.h"
#include "SevenZipArchiveItem.h"

using namespace SevenZip;

HRESULT RightSubstringUpTo(CONST CString & Str, WCHAR UpTo, CString & Result, BOOL IncludeChar = FALSE) 
{
	HRESULT hr = E_FAIL;
	INT index = -1;

	index = Str.ReverseFind(UpTo);

	if (index < 0)
	{
		Result = Str;
		hr = S_FALSE;
	}
	else
	{
		if (!IncludeChar)
		{
			index += 1;
		}

		Result = Str.Mid(index);
		hr = S_OK;
	}

	return hr;
}

SevenZip::CSevenZipArchiveItem::CSevenZipArchiveItem()
	: _Index(UINT32_MAX)
	, _Archive(NULL)
{
}

SevenZip::CSevenZipArchiveItem::CSevenZipArchiveItem(CComPtr<IInArchive> & Archive)
	: _Index(UINT32_MAX)
	, _Archive(Archive)
{
}

SevenZip::CSevenZipArchiveItem::CSevenZipArchiveItem(CComPtr<IInArchive> & Archive, UINT32 Index)
	: _Archive(Archive)
	, _Index(Index)
{
}

SevenZip::CSevenZipArchiveItem::~CSevenZipArchiveItem()
{
	BOOST_FOREACH(CSevenZipArchiveItem * i, _ChildItems)
	{
		delete i;
	}
}

STDMETHODIMP SevenZip::CSevenZipArchiveItem::GetType(CStringW & Type) CONST
{
	HRESULT hr;
	BOOL f;

	if (SUCCEEDED(hr = IsFolder(&f)))
	{
		if (f)
		{
			Type = L"Folder";
			hr = S_OK;
		}
		else
		{
			CStringW Name;

			if (SUCCEEDED(hr = GetName(Name)))
			{
				hr = RightSubstringUpTo(Name, L'.', Type, TRUE);
			}
		}
	}

	return hr;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItem::GetName(CStringW & Name) CONST
{
	CStringW Path;
	HRESULT hr;

	if (SUCCEEDED(hr = GetPath(Path)))
	{
		hr = RightSubstringUpTo(Path, L'\\', Name);
	}

	return hr;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItem::GetPath(CStringW & Path) CONST
{
	HRESULT hr = S_OK;

	if (_Path.IsEmpty())
	{
		CComMemPtr<WCHAR> PathBuffer;

		if (SUCCEEDED(hr = GetPropertyValue(ITEMPROP_Path, PathBuffer)))
		{
			_Path = PathBuffer;
		}
	}

	if (SUCCEEDED(hr))
	{
		Path = _Path;
	}

	return hr;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItem::GetParentPath(CStringW & ParentPath) CONST
{
	HRESULT hr;
	CComMemPtr<WCHAR> Path;

	if (SUCCEEDED(hr = GetPropertyValue(ITEMPROP_Path, Path)))
	{
		if (::PathRemoveFileSpecW(Path))
		{
			if ((Path != NULL) && (*Path != L'\0'))
			{
				ParentPath = Path;
			}
		}

		hr = S_OK;
	}

	return hr;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItem::IsFolder(PBOOL Result) CONST
{
	HRESULT hr = E_FAIL;
	CComPropVariant Value;

	if (SUCCEEDED(hr = GetPropertyValue(ITEMPROP_IsDirectory, Value)))
	{
		hr = Value.ToBoolean(Result);
	}

	return hr;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItem::GetPropertyValue(PROPID PropID, CComMemPtr<WCHAR> & Value) CONST
{
	HRESULT hr;
	CComPropVariant PropVar;

	if (SUCCEEDED(hr = GetPropertyValue(PropID, PropVar)))
	{
		hr = PropVar.ToString(&Value);
	}

	return hr;
}

STDMETHODIMP SevenZip::CSevenZipArchiveItem::GetPropertyValue(PROPID PropID, CComPropVariant & Value) CONST
{
	return _Archive->GetProperty(_Index, PropID, &Value);
}
